package com.kelaite.procurement.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.dto.CompanyDTO;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TMessage;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.restful.BaseController;
import com.kelaite.procurement.service.MessageService;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.utils.ConvertUtil;

/**
 * 
 * @author yuanchangwei
 *
 */
@Controller
@RequestMapping("/message")
public class MessageController extends BaseController{
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
	public String index(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, Model model) {
		try {
			UserDTO userDto = getCurrentUser(session);
			List<TMessage> messageList = this.messageService.getUndeletedMessage(ConvertUtil.convertObj(userDto, TUser.class));
			model.addAttribute("totalMessage", messageList.size());
			model.addAttribute("messageList", messageList);
			CompanyDTO company = userDto.gettCompany();
			model.addAttribute("type", company.getBusinessType());
		} catch (Exception e) { 
			
			logger.error(e.getMessage());
			return "error";
		}
		return "message/message_index";
	}
	
	/**
	 * 用户删除消息
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public String deleteMessage(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, Model model) throws Exception {
		try {
			String messageId = request.getParameter("msg_id");
			TMessage messageObj = this.messageService.getObject(Long.parseLong(messageId));
			messageObj.setIsDeleted(Constants.USER_MESSAGE_DELETED);
			this.messageService.save(messageObj);
			return this.index(request, response, session, model);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "error";
		}
	}

	@Override
	protected Class<?> getCurrentClass() {
		return MessageController.class;
	}
}
